package com.example.project_01.service.impl;

import com.example.project_01.commons.Result;
import com.example.project_01.pojo.City;
import com.example.project_01.entity.CityEntity;
import com.example.project_01.mapper.CityMapper;
import com.example.project_01.model.CityModel;
import com.example.project_01.service.CityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service
public class CityServiceImpl implements CityService {

    @Autowired
    CityMapper cityMapper;

    /*获取所有城市信息并分页，name不为空则模糊查询,当pn和size为null,则整页查询
    * pn：页码
    * size：每页大小
    * */
    @Override
    public PageInfo<CityModel> getCityWithPage(Integer pn, Integer size, String name) {
        if (pn == null && size == null){
            pn = 1;   //默认第一页
            size = 0;   //表示查询所有数据，不分页
        }
        PageHelper.startPage(pn, size);   //启动分页
        List<CityModel> list = cityMapper.getAllCity(name);
        PageInfo<CityModel> info = new PageInfo<>(list);   //将查询结果封装成PageInfo对象
        return info;
    }

    //根据id查找城市信息
    @Override
    public Result getCityById(Integer id) {
        City city = cityMapper.getCityById(id);
        if (city != null){
            return new Result(200,"成功通过id查找城市信息",city);
        }
        return new Result(201,"没有找到城市信息",null);
    }

    //添加一个城市
    @Override
    public Result addCity(Integer cityNumber) {
        City city = new City();
        Date date = new Date();
        city.setCityNumber(cityNumber);
        city.setCreateTime(date);
        city.setUpdateTime(date);

        CityEntity cityEntity = new CityEntity();
        //对象拷贝
        BeanUtils.copyProperties(city,cityEntity);

        System.out.println("当前时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
        System.out.println("JVM时区：" + TimeZone.getDefault().getID());

        //执行添加操作
        int row = cityMapper.addCity(cityEntity);
        if (row > 0){
            Long num = cityEntity.getTotal() % 5 == 0 ? (cityEntity.getTotal() / 5) : (cityEntity.getTotal() / 5) + 1;
            return new Result(200,"城市信息添加成功！",num);
        }
        return new Result(201,"城市信息添加失败",null);
    }

    //检查城市是否存在
    @Override
    public int checkCityByNum(Integer cityName) {
        return cityMapper.checkCityByNum(cityName);
    }

    //根据id删除城市信息
    @Override
    public Result deleteCityById(Integer id) {
        int row = cityMapper.delectCityById(id);
        //根据城市删除医保政策
        //medicalPolicyMapper.deleteByCity(id);
        if (row > 0){
            return new Result(200,"删除成功！",null);
        }
        return new Result(202,"删除失败！城市id错误",null);
    }

}
